package com.cq.hd.order.factory.orderSelect;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cq.hd.common.enums.ResponseEnums;
import com.cq.hd.common.enums.biz.AgentStateEnum;
import com.cq.hd.common.enums.biz.CalCommissionTypeEnum;
import com.cq.hd.common.enums.biz.OrderSelectTypeEnum;
import com.cq.hd.common.enums.biz.RewardTypeEnum;
import com.cq.hd.common.pagination.Page;
import com.cq.hd.common.response.Throw;
import com.cq.hd.order.api.dto.AppOrderDetailDto;
import com.cq.hd.order.api.dto.AppOrderPageDto;
import com.cq.hd.order.api.vo.AppOrderCommissionVo;
import com.cq.hd.order.api.vo.AppOrderDetailVo;
import com.cq.hd.order.api.vo.AppOrderPageVo;
import com.cq.hd.order.mapper.TbOrderItemMapper;
import com.cq.hd.order.mapper.TbOrderMapper;
import com.cq.hd.order.po.TbOrderItemPo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@Slf4j
public class AgentOrderSelectHandler extends AbstractOrderSelectHandler {

    @Autowired
    private TbOrderMapper orderMapper;

    @Autowired
    private TbOrderItemMapper orderItemMapper;

    @Override
    protected Integer getType() {
        return OrderSelectTypeEnum.AGENT.getValue();
    }

    @Override
    public Page<AppOrderPageVo> pageAppOrder(AppOrderPageDto appOrderPageDto) {
        Long userId = appOrderPageDto.getUserId();
        if (userId == null || userId <= 0) {
            Throw.isBusinessException(ResponseEnums.USER_ACCESS_DENIED);
        }
        appOrderPageDto.setAgentId(userId);

        PageHelper.startPage(appOrderPageDto.getPageNum(), appOrderPageDto.getPageSize());
        List<AppOrderPageVo> orderPageVoList;
        // 分销订单类型：1自推订单 2团队订单
        Integer subOrderType = appOrderPageDto.getSubOrderType();
        if (subOrderType == null || subOrderType == 1) {
            orderPageVoList = orderMapper.listAppAgentSelfOrderByDto(appOrderPageDto);
        } else {
            orderPageVoList = orderMapper.listAppAgentTeamOrderByDto(appOrderPageDto);
        }
        if (!CollectionUtils.isEmpty(orderPageVoList)) {
            List<Long> orderIds = orderPageVoList.stream().map(AppOrderPageVo::getId).collect(Collectors.toList());

            Map<Long, List<TbOrderItemPo>> orderItemMap = new HashMap<>();
            // 根据订单id查询子订单列表
            List<TbOrderItemPo> tbOrderItemPos = orderItemMapper.selectList(new QueryWrapper<TbOrderItemPo>().eq("del_state", 0)
                    .in("order_id", orderIds));
            if (!CollectionUtils.isEmpty(tbOrderItemPos)) {
                orderItemMap = tbOrderItemPos.stream().collect(Collectors.groupingBy(TbOrderItemPo::getOrderId));
            }

            for (AppOrderPageVo appOrderPageVo : orderPageVoList) {
                Long agentId = appOrderPageVo.getAgentId();
                Long agent2Id = appOrderPageVo.getAgent2Id();
                // 分销开启状态(1-关闭，2-开启)
                Integer agentState = appOrderPageVo.getAgentState();
                // 计算佣金类型(0-无,1-固定佣金,2-专属佣金比例)
                Integer calCommissionType = appOrderPageVo.getCalCommissionType();

                // 如果开启了分销，且计算佣金类型不是无，如果是卖出订单，则需要处理佣金，如果是分销的订单，判断订单分销经纪人id是否与当前用户id一致，一致也需要处理佣金
                // 如果开启了分销，且计算佣金类型是无，如果是卖出订单，则需要返回推广权益，如果是分销的订单，判断订单分销经纪人id是否与当前用户id一致，一致也需要返回推广权益
                if (AgentStateEnum.OPEN.getValue().equals(agentState) && agentId > 0) {
                    if (userId.equals(agentId) || userId.equals(agent2Id)) {
                        // 处理佣金或返回推广权益
                        if (!CalCommissionTypeEnum.NO.getValue().equals(calCommissionType)) {
                            AppOrderCommissionVo appOrderCommissionVo = new AppOrderCommissionVo();
                            BeanUtils.copyProperties(appOrderPageVo, appOrderCommissionVo);
                            appOrderCommissionVo.setUserId(userId);
                            appOrderPageVo.setCommissionAmt(promotionEquityHandle(orderItemMap, appOrderCommissionVo));
                            appOrderPageVo.setOtherEquity("");
                            appOrderPageVo.setRewardType(RewardTypeEnum.COMMISSION.getValue());
                        } else {
                            // 积分
                            setOrderPageRewardPoints(appOrderPageVo, userId);
                        }
                    } else {
                        appOrderPageVo.setOtherEquity("");
                    }
                } else {
                    appOrderPageVo.setOtherEquity("");
                }
            }
        }
        PageInfo<AppOrderPageVo> pageInfo = new PageInfo<>(orderPageVoList);
        return Page.newPageWithAllFields(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages());
    }

    @Override
    public AppOrderDetailVo appOrderDetail(AppOrderDetailDto appOrderDetailDto) {
        String orderNo = appOrderDetailDto.getOrderNo();
        Long id = appOrderDetailDto.getId();
        if (id == null || id <= 0) {
            if (StringUtils.isEmpty(orderNo)) {
                Throw.isBusinessException("未找到订单数据");
            }
            Throw.isBusinessException("未找到订单数据");
        }

        Long userId = appOrderDetailDto.getUserId();
        if (userId == null || userId <= 0) {
            Throw.isBusinessException(ResponseEnums.USER_ACCESS_DENIED);
        }
        appOrderDetailDto.setAgentId(userId);

        AppOrderDetailVo appOrderDetailVo = orderMapper.getAppAgentOrderByDto(appOrderDetailDto);
        if (appOrderDetailVo == null) {
            Throw.isBusinessException("未找到订单数据");
        }

        // 分销开启状态(1-关闭，2-开启)
        Integer agentState = appOrderDetailVo.getAgentState();
        // 计算佣金类型(0-无,1-固定佣金,2-专属佣金比例)
        Integer calCommissionType = appOrderDetailVo.getCalCommissionType();
        Long agentId = appOrderDetailVo.getAgentId();
        Long agent2Id = appOrderDetailVo.getAgent2Id();

        // 如果开启了分销，且计算佣金类型不是无，如果是卖出订单，则需要处理佣金，如果是分销的订单，判断订单分销经纪人id是否与当前用户id一致，一致也需要处理佣金
        // 如果开启了分销，且计算佣金类型是无，如果是卖出订单，则需要返回推广权益，如果是分销的订单，判断订单分销经纪人id是否与当前用户id一致，一致也需要返回推广权益
        if (AgentStateEnum.OPEN.getValue().equals(agentState) && appOrderDetailVo.getAgentId() > 0) {
            if (!CalCommissionTypeEnum.NO.getValue().equals(calCommissionType)) {
                Map<Long, List<TbOrderItemPo>> orderItemMap = new HashMap<>();
                // 根据订单id查询子订单列表
                List<TbOrderItemPo> tbOrderItemPos = orderItemMapper.selectList(new QueryWrapper<TbOrderItemPo>().eq("del_state", 0)
                        .eq("order_id", appOrderDetailVo.getId()));
                if (!CollectionUtils.isEmpty(tbOrderItemPos)) {
                    orderItemMap = tbOrderItemPos.stream().collect(Collectors.groupingBy(TbOrderItemPo::getOrderId));
                }

                // 处理佣金或返回推广权益
                appOrderDetailVo.setOtherEquity("");
                if (userId.equals(agentId) || userId.equals(agent2Id)) {
                    AppOrderCommissionVo appOrderCommissionVo = new AppOrderCommissionVo();
                    BeanUtils.copyProperties(appOrderDetailVo, appOrderCommissionVo);
                    appOrderCommissionVo.setUserId(userId);
                    appOrderDetailVo.setCommissionAmt(promotionEquityHandle(orderItemMap, appOrderCommissionVo));
                    appOrderDetailVo.setRewardType(RewardTypeEnum.COMMISSION.getValue());
                } else {
                    appOrderDetailVo.setOtherEquity("");
                }
            } else {
                // 积分
                setOrderDetailRewardPoints(appOrderDetailVo, userId);
            }
        } else {
            appOrderDetailVo.setOtherEquity("");
        }

        return appOrderDetailVo;
    }
}
